package com.etc.demo1.demo.controller;


import com.etc.demo1.demo.domain.Goods;
import com.etc.demo1.demo.service.GoodsService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class GoodsController {
    private GoodsService goodsService;

    //查询全部
    @RequestMapping("/list")
    public String goodsList(Model model){
        List<Goods> goods=goodsService.findAll();
        model.addAttribute("goods",goods);
        return "index";
    }

    //新增数据
    @RequestMapping("/add")
    public String save(Goods goods){
        goodsService.save(goods);
        return "redirect:/list";
    }

    //删除数据
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpServletResponse servletResponse) throws IOException {
        int count=goodsService.delete(id);
        if (count==1){
            servletResponse.sendRedirect("/list");
        }
        return "error";
    }

    //根据id查找
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model,@PathVariable int id){
        Goods goods=goodsService.getGoodsById(id);
        model.addAttribute("goods",goods);
        return "modifi";
    }

    //更新数据
    @PostMapping("/update")
    public String updateUser(Model model, Goods goods, HttpServletRequest request){
        String id=request.getParameter("id");
        Goods userByid=goodsService.getGoodsById(Integer.parseInt(id));
        goodsService.update(goods);
        System.out.println(goods);
        return "redirect:/list";
    }
}
